package biz

import (
	"time"

	"github.com/golang-jwt/jwt/v4"
)

/**
 * @description 生成JWT token
 * @param userId int64 用户ID
 * @param username string 用户名
 * @param accessSecret string JWT密钥
 * @param accessExpire int64 过期时间(秒)
 * @return string token字符串
 * @return error 错误信息
 */
func GenerateToken(userId any, accessSecret string, accessExpire int64) (string, error) {
	now := time.Now().Unix()
	claims := make(jwt.MapClaims)
	claims["exp"] = now + accessExpire
	claims["iat"] = now
	claims["userId"] = userId

	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims

	return token.SignedString([]byte(accessSecret))
}

/**
 * @description 解析JWT token
 * @param tokenString string token字符串
 * @param accessSecret string JWT密钥
 * @return jwt.MapClaims token claims
 * @return error 错误信息
 */
func ParseToken(tokenString string, accessSecret string) (jwt.MapClaims, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(accessSecret), nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims, nil
	}

	return nil, err
}
